package com.gouda.temporary.utils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.util.Date;
//import org.dom4j.Document;
//import org.dom4j.DocumentException;
//import org.dom4j.DocumentHelper;
//import org.dom4j.Element;
//import org.dom4j.io.SAXReader;
//import org.dom4j.io.XMLWriter;

import javax.net.ssl.SSLContext;

import com.google.gson.GsonBuilder;
import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HongbaoUtils {

    private static final Logger log = LoggerFactory.getLogger(HongbaoUtils.class);
    public static void main(String args[]) {

        String Userid= "8ad202fd27afeca921460afd3cb68594";
       /* String url = "https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_openid?access_token=x0zygpqF-U9Pc1ktT7CbbfqVBP62whVwg5huAC_RqPBgUibChaJhxW98CjSd8csikGWEAwc6cDk5p2X7Uut0uw";
        //冯总 eebba5c0906d9bedfa190056a8cda761
        //罗总  f20e9c98f10280adb384edaf6a61f978
        //司树行userid 8ad202fd27afeca921460afd3cb68594
        //周能发userid 2034960cb4d928a21f05411505ad4f00
        //芳芳userid 3335a3c7819133831a63a4a18acf575b
        //张韦userid a50d0adea730fb3644c1fcf6b4781078
        String PostJson = "{\"userid\":\"" + Userid + "\"}";
        //System.out.println(openjson);
        String openjson = XYHttpUtils.doPost(url,PostJson);
        System.out.println("openjson"+openjson);*/
        String token ="5QIm3lEUXeINwh2pbBbdFQixzK72S8ZYoib1RToZgX_mnxfiweWlFyr4RN6P_xIpEhzj7Az0-YpZpRQaOdlK7g";
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_openid?access_token=" + token;
        String PostJson="{\"userid\":\""+Userid+"\",\"agentid\":39}";

        String openjson = XYHttpUtils.doPost(url, PostJson);
        Open open =gsonParseObject(openjson, Open.class);
        log.info(">>>> 人员信息-红包发送: appid={}, openjson={}, PostJson={} openid={}, token={}", open.getAppid(), openjson, PostJson, open.getOpenid(), token);
        HongbaoUtils hb = new HongbaoUtils();
       hb.sendRedEnvelop(open.getOpenid(), open.getAppid(),"102","","");
    }



    public static <T> T gsonParseObject(String text, Class<T> clazz) {
        try {
            return new GsonBuilder().disableHtmlEscaping().create().fromJson(text, clazz);
        } catch (Throwable e) {
            log.error("Gson fromJson error", e);
            return null;
        }
    }

    public String sendRedEnvelop(String openId,String appId,String money,String corpid,String type) {
        String noncestr = randomChars(32);// 随机字符串
        //noncestr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
        String url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
        String mch_id = "1296667801"; // 商户号
        String mch_billno = getMchBillno(mch_id); // 商户订单号
        //mch_billno = "129666780120151216f25nMeDXs3";
        String wxappid = appId; // 公众账号appid
        String send_name = "爱接力"; // 商户名称
        String total_amount = money; // 付款金额
        String total_num = "1"; // 红包发放总人数
        String wishing = "恭喜发财"; // 红包祝福语
        String client_ip = "123.56.127.135"; // 调用接口的机器Ip地址
        String act_name = "首次关注有奖"; // 活动名称
        String remark = "感谢您的加入"; // 备注
        String key = "66bc175902c1d3dec5ef4b3be298e088"; // API密钥

        // TreeMap自动按ASCII码从小到大排序
        Map<String, String> map = new TreeMap<String, String>();
        map.put("nonce_str", noncestr);
        map.put("mch_billno", mch_billno);
        map.put("mch_id", mch_id);
        map.put("wxappid", wxappid);
        map.put("send_name", send_name);
        map.put("re_openid", openId);
        map.put("total_amount", total_amount);
        map.put("total_num", total_num);
        map.put("wishing", wishing);
        map.put("client_ip", client_ip);
        map.put("act_name", act_name);
        map.put("remark", remark);
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        Set<Map.Entry<String, String>> set = map.entrySet();
        StringBuffer sb = new StringBuffer();
        // 取出排序后的参数，逐一连接起来
        for (Iterator<Map.Entry<String, String>> it = set.iterator(); it.hasNext(); ) {
            Map.Entry<String, String> me = it.next();
            sb.append(me.getKey() + "=" + me.getValue() + "&");
            formparams.add(new BasicNameValuePair(me.getKey(), me.getValue()));
        }
        String stringsign = sb.append("key=" + key).toString();
        String sign = MD5(stringsign).toUpperCase();
         try {
            HttpClient httpclient = checkCertificate();
            String body =sendByPost(httpclient, genXml(formparams, sign), url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    public String sendByPost(HttpClient httpclient, String entitys, String url) throws Exception {
        String result="";
        try {
            HttpPost httpPost = new HttpPost(url);// 创建HttpPost对象
            if (entitys != null) {
                StringEntity postEntity = new StringEntity(entitys, Consts.UTF_8);
                httpPost.setEntity(postEntity);
            }
            httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
            CloseableHttpResponse response = (CloseableHttpResponse) httpclient.execute(httpPost);
            try {
                String respBody = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
                result =respBody;
                System.out.println(respBody);
                System.out.println("----------------------------------------");
            } finally {
                response.close();
            }
        } finally {
        }
        return result;
    }
    // 随机字符串
    public String randomChars(int num) {
        Random random = new Random();
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        String str = "";
        for (int i = 0; i < num; i++) {
            str += chars.charAt(random.nextInt(62));
        }
        return str;
    }
    public String genXml(List<NameValuePair> params, String sign) {
        StringBuilder sb2 = new StringBuilder();

        sb2.append("<?xml version='1.0' encoding='UTF-8' ?><xml>");
        for (int i = 0; i < params.size(); i++) {
            // sb2是用来做请求的xml参数
            sb2.append("<" + params.get(i).getName() + ">");
            //sb2.append(params.get(i).getValue());
            sb2.append("<![CDATA["+params.get(i).getValue()+"]]>");
            sb2.append("</" + params.get(i).getName() + ">");
            System.out.print(params.get(i));
        }
        /*sb2.append("<sign>");
        sb2.append(sign);
        sb2.append("</sign>");*/
        sb2.append("<sign><![CDATA[");
        sb2.append(sign);
        sb2.append("]]></sign>");

        sb2.append("</xml>");
        try {
            return sb2.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    public CloseableHttpClient checkCertificate() throws Exception {

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        FileInputStream instream = new FileInputStream(
                //new File("C:\\apiclient_cert.p12")
                new File("/opt/app/webapp/WEB-INF/classes/apiclient_cert.p12")
        );
        try {
            keyStore.load(instream, "1296667801".toCharArray());
        } finally {
            instream.close();
        }
        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "1296667801".toCharArray()).build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, "TLSv1".split(" "), null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        return httpclient;
    }
    public final static String MD5(String s) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            byte[] btInput = s.getBytes("UTF-8");
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public String getMchBillno(String mch_id) {
        // 商户订单号（每个订单号必须唯一）
        // 组成： mch_id+yyyymmdd+10位一天内不能重复的数字。
        // 接口根据商户订单号支持重入， 如出现超时可再调用。
        SimpleDateFormat t = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        String time = t.format(date);
        return mch_id + time + randomChars(10);
    }
    public static String MD5Encode(String origin) {
        String resultString = null;
        try {
            resultString = origin;
            MessageDigest md = MessageDigest.getInstance("MD5");
            // resultString = byteArrayToHexString(md.digest(resultString.getBytes()));//原文件内容，可能原因是：win2003时系统缺省编码为GBK，win7为utf-8
            resultString = bytesToHexString(md.digest(resultString.getBytes("utf-8")));//正确的写法
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultString;
    }
    public static final String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }
}
